package seotools.positions.top;


import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.codehaus.plexus.util.StringInputStream;
import org.codehaus.plexus.util.StringOutputStream;

import java.io.*;

public class FTPHelper {
    private static final String HOST = "78.108.80.70";
    private static final String LOGIN = "f115634";
    private static final String PASS = "webst@rstud1o";

    private FTPClient client;

    public FTPHelper(String host, String login, String pass) throws IOException {
        login(host, login, pass);
    }

    public FTPHelper() throws IOException {
        login(HOST, LOGIN, PASS);
    }

    private void login(String host, String login, String pass) throws IOException {
        client = new FTPClient();
        client.connect(host);
        client.login(login, pass);
        client.setFileType(FTP.BINARY_FILE_TYPE);
    }

    private void logout() throws IOException {
        client.logout();
    }

    public static void main(String[] args) throws IOException {
        FTPClient client = new FTPClient();
        client.connect("78.108.80.70");
        client.login("f115634", "webst@rstud1o");
        client.changeWorkingDirectory("logs");
        String[] names = client.listNames();
        StringOutputStream s = new StringOutputStream();
        for (String name : names) {
            if (name.contains("extramobi.ru")) {
                client.retrieveFile(name, s);
                System.out.println(s.toString());
            }
        }
//        client.changeWorkingDirectory("/extramobiru/www/temp");
//        String filename = "accum.lg.txt";
//        ByteArrayInputStream is = new ByteArrayInputStream("blabla".getBytes());
//        client.storeFile(filename, is);
//        String[] names = client.listNames();
//        for (String name : names) {
//            System.out.println("Name = " + name);
//        }
        client.logout();
        client.disconnect();
    }

    public String[] listFiles(String dirName) throws IOException {
        client.changeWorkingDirectory(dirName);
        return client.listNames();
    }

    public InputStream readFile(String fileName) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        client.retrieveFile(fileName, out);
        return new ByteArrayInputStream(out.toByteArray());
    }

    public static void writeToTemp(String filename, String content) throws IOException {
        FTPClient client = new FTPClient();
        client.connect("78.108.80.70");
        client.login("f115634", "webst@rstud1o");
        client.changeWorkingDirectory("/extramobiru/www/temp");
        ByteArrayInputStream is = new ByteArrayInputStream(content.getBytes());
        client.storeFile(filename, is);
        client.logout();
        client.disconnect();
    }

}
